﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
using System.Data.Linq.Mapping;

namespace SQLite2CELib
{
    public class PropertyDetails
    {
        public String Name { get; set; }
        public Type TypeInfo { get; set; }
    }

    public class TableSchemaHelper
    {
        private Assembly _assembly;

        public void Initialize(String locationOfEntityClassAssembly)
        {
            _assembly = Assembly.LoadFile(locationOfEntityClassAssembly);
        }

        public Dictionary<String, PropertyDetails> GetClassNameAndTypeInfo(String columnName)
        {
            Type[] typesInAssembly;
            PropertyInfo matchingProperty;
            Dictionary<String, PropertyDetails> classNameAndTypeInfo;

            typesInAssembly = _assembly.GetTypes();
            classNameAndTypeInfo = new Dictionary<String, PropertyDetails>();

            foreach (Type type in typesInAssembly)
            {
                matchingProperty = type.GetProperties().Where(eachProperty => String.Compare(eachProperty.Name, columnName, StringComparison.OrdinalIgnoreCase) == 0).FirstOrDefault();
                if (matchingProperty != null)
                {
                    //Assumption - Spaces that occur in the Name of Tables are removed when tool converts it into sqlce.
                    classNameAndTypeInfo.Add(type.Name.Replace(" ", String.Empty), new PropertyDetails { Name = matchingProperty.Name, TypeInfo = matchingProperty.PropertyType });
                }
            }
            return classNameAndTypeInfo;
        }

        public Type GetTypeInfoByName(String typeName)
        {
            Type matchingType;
            Type[] typesInAssembly;

            typesInAssembly = _assembly.GetTypes();
            matchingType = (from eachType in typesInAssembly
                            where eachType.Name == typeName
                            select eachType).FirstOrDefault();
            return matchingType;
        }

        public String GetClassNameForTableName(String tableName)
        {
            String matchingTypeName;
            Type[] typesInAssembly;

            typesInAssembly = _assembly.GetTypes();
            matchingTypeName = (from eachType in typesInAssembly
                               where String.Compare(eachType.Name, 
                                                    tableName.Replace(" ", String.Empty), 
                                                    StringComparison.InvariantCultureIgnoreCase) == 0
                               select eachType.Name).FirstOrDefault();
            return matchingTypeName;
        }
    }
}
